package com.zjjh.gateway.utils;

import com.alibaba.fastjson.JSON;
import com.ares.basic.exception.BusinessException;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;

import java.util.HashMap;
import java.util.Map;

public class ResponseUtil {

    public static DataBuffer getResponseBuf(ServerHttpResponse response, Throwable ex) {
        response.getHeaders().add("contentType", "application/json; charset=utf-8");
        DataBuffer dataBuffer = null;
        if (ex instanceof BusinessException){
            BusinessException bus = (BusinessException) ex;
            Map<String, Object> result = new HashMap<>();
            result.put("code", bus.getCode());
            result.put("msg", ex.getMessage());
            dataBuffer = response.bufferFactory().wrap(JSON.toJSONBytes(result));
        }else {
            Map<String, Object> result = new HashMap<>();
            result.put("code", "500");
            result.put("msg", ex.getMessage());
            dataBuffer = response.bufferFactory().wrap(JSON.toJSONBytes(result));
        }
        return dataBuffer;
    }

}
